package com.skivingcloud.admin.sys.controller;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.skivingcloud.admin.conf.RequestLock;
import com.skivingcloud.admin.constants.Constant;
import com.skivingcloud.admin.logutils.OperateLog;
import com.skivingcloud.admin.security.SecurityUser;
import com.skivingcloud.admin.security.UserUtil;
import com.skivingcloud.admin.sys.entity.*;
import com.skivingcloud.admin.sys.service.SysMenuService;
import com.skivingcloud.admin.sys.service.SysRoleMenuService;
import com.skivingcloud.admin.sys.service.SysRoleService;
import com.skivingcloud.admin.sys.service.SysUserRoleService;
import com.skivingcloud.common.exceptions.BusinessException;
import com.skivingcloud.common.utils.PageParameter;
import com.skivingcloud.common.utils.ReturnT;
import com.skivingcloud.common.utils.UuidUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  控制层。
 *
 * @author skivingcloud
 * @since 2023-08-28
 */
@Tag(name = "SysRoleController", description = "角色管理API")
@RestController
@RequestMapping("/sysRole")
public class SysRoleController {
    
    private static final Logger log = LoggerFactory.getLogger(SysRoleController.class);
    
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysRoleMenuService sysRoleMenuService;
    @Resource
    private SysMenuService sysMenuService;
    @Resource
    private SysUserRoleService sysUserRoleService;
    /**
     * 添加。
     *
     * @param sysRole 角色信息
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @Operation(summary = "新增角色", description = "新增角色")
    @ApiResponse(responseCode = "2xx",description = "新增角色")
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:role:add')")
    @RequestLock
    @OperateLog(module="系统管理", description = "新增角色")
    public ReturnT<Boolean> save(@Validated @RequestBody SysRole sysRole) {
        try{
            sysRole.setId(UuidUtil.get32UUID());
            sysRole.setCreateUserId(UserUtil.getCurrentUser().getId());
            sysRole.setCreateTime(LocalDateTime.now());
            return ReturnT.ok(sysRoleService.saveHasRes(sysRole));
        }catch(Exception e){
            log.error("保存角色失败", e);
            return ReturnT.error("保存角色失败！");
        }
    }

    /**
     * 根据主键删除。
     *
     * @param id 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @Operation(summary = "删除角色", description = "角色",
            parameters = {@Parameter(name = "ids", description = "角色id")})
    @ApiResponse(responseCode = "2xx",description = "删除角色")
    @GetMapping("/remove/{id}")
    @PreAuthorize("hasAuthority('sys:role:delete')")
    @OperateLog(module="系统管理", description = "删除角色")
    public ReturnT<String> remove(@PathVariable(name="id") Serializable id) {
        try{
            sysRoleService.removeByIdRelations(id);
            return ReturnT.ok("删除角色成功");
        }catch(IllegalArgumentException | BusinessException e){
            log.error(e.getMessage(), e);
            return ReturnT.error(e.getMessage());
        }catch(Exception e){
            log.error("删除角色失败", e);
            return ReturnT.error("删除角色失败");
        }
    }
    
    /**
     * 根据主键更新。
     *
     * @param sysRole 角色信息
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @Operation(summary = "修改角色", description = "修改角色")
    @ApiResponse(responseCode = "2xx",description = "修改角色")
    @PreAuthorize("hasAuthority('sys:role:update')")
    @PostMapping("/update")
    @OperateLog(module="系统管理", description = "修改角色")
    public ReturnT<Boolean> update(@Validated @RequestBody SysRole sysRole) {
        try{
            sysRole.setModUserId(UserUtil.getCurrentUser().getId());
            sysRole.setModTime(LocalDateTime.now());
            return ReturnT.ok(sysRoleService.updateByIdHasRes(sysRole));
        }catch(Exception e){
            log.error("保存角色失败", e);
            return ReturnT.error("保存角色失败！");
        }
    }
    
    /**
     * 根据主键获取详细信息。
     *
     * @param id 主键
     * @return 详情
     */
    @GetMapping("getInfo/{id}")
    @Operation(summary="根据id查询角色信息")
    public SysRole getInfo(@PathVariable(name="id") Serializable id) {
        return sysRoleService.getById(id);
    }

    
    /**
     * 分页查询角色
     * @param parameter 查询参数
     * @return 分页查询结果
     */
    @Operation(summary = "分页查询角色", description = "角色列表",
            parameters = {@Parameter(name = "parameter", description = "分页查询条件")})
    @ApiResponse(responseCode = "2xx",description = "分页角色列表")
    @PostMapping("/queryRoleListPage")
    public ReturnT<Page<SysRole>> queryRoleListPage(@RequestBody PageParameter<SysRole> parameter){
        Page<SysRole> page = sysRoleService.queryByPage(parameter);
        return ReturnT.ok(page);
    }
    
    /**
     * 根据租户和角色id加载资源树权限
     *
     * @param tenantId 租户ID
     * @param id 角色ID
     * @return 资源权限
     */
    @Operation(summary = "根据租户和角色id加载资源树权限", description = "根据租户和角色id加载资源树权限",
            parameters = {@Parameter(name = "tenantId, id", description = "租户id，角色id")})
    @ApiResponse(responseCode = "2xx",description = "根据租户和角色id加载资源树权限")
    @GetMapping("/resetTenantRoleResTree/{tenantId}/{id}")
    public ReturnT<Map<String, Object>> resetTenantRoleResTree(@PathVariable("tenantId") String tenantId, @PathVariable("id") String id){
        SecurityUser user = UserUtil.getCurrentUser();
        if (!user.getTenantId().equals(Constant.SUPER_ADMIN_TENANT_ID)) {
            tenantId = user.getTenantId();
        }
        if (tenantId == null) {
            return ReturnT.error("租户不明确没数据");
        }
        List<SysMenu> list = sysMenuService.getTenantMenuList(tenantId);
        List<SysRoleMenu> asingRes = new ArrayList<>();
        if(StringUtils.isNotBlank(id)){
            QueryWrapper queryWrapper = QueryWrapper.create();
            queryWrapper.where(SysRoleMenu::getRoleId).eq(id);
            asingRes = sysRoleMenuService.list(queryWrapper);
        }
        Map<String, Object> res = new HashMap<>();
        res.put("tree", list);
        res.put("asingRes", asingRes);
        return ReturnT.ok(res);
    }
    
    /**
     * 设置角色资源权限
     * @param sysRole 角色资源信息
     * @return 结果
     */
    @Operation(summary = "设置角色资源权限", description = "设置角色资源权限")
    @ApiResponse(responseCode = "2xx",description = "设置角色资源权限")
    @PreAuthorize("hasAuthority('sys:role:setmenu')")
    @PostMapping("/setRoleMenu")
    @OperateLog(module="系统管理", description = "设置角色资源权限")
    public ReturnT<String> setRoleMenu(@RequestBody SysRole sysRole) {
        try {
            sysRoleService.saveRoleRes(sysRole.getId(), sysRole.getResId());
            return ReturnT.ok();
        } catch (Exception e) {
            log.error("设置资源权限失败", e);
            return ReturnT.error("设置资源权限失败");
        }
    }
    
    /**
     * 查询用户角色关系
     * @param parameter 参数
     * @return 结果
     */
    @Operation(summary = "分页查询角色下的用户", description = "分页查询角色下的用户",
            parameters = {@Parameter(name = "parameter", description = "分页查询条件")})
    @ApiResponse(responseCode = "2xx",description = "分页查询角色下的用户")
    @PostMapping("/getRoleUserDataListByRoleId")
    public ReturnT<Page<SysUserRole>> getRoleUserDataListByRoleId(@RequestBody PageParameter<SysUserRole> parameter){
        if(parameter.getParam().getRoleId().isEmpty()){
            return ReturnT.error("必须选择一条角色记录");
        }
        Page<SysUserRole> page = sysUserRoleService.queryByPage(parameter);
        return ReturnT.ok(page);
    }
    
    /**
     * 查询没设置该角色的用户
     * @param parameter 参数
     * @return 参数
     */
    @Operation(summary = "查询没设置该角色的用户", description = "查询没设置该角色的用户",
            parameters = {@Parameter(name = "parameter", description = "分页查询条件")})
    @ApiResponse(responseCode = "2xx",description = "查询没设置该角色的用户")
    @PostMapping("/getRoleUserSelectListByRoleId")
    public ReturnT<Page<SysUser>> getRoleUserSelectListByRoleId(@RequestBody PageParameter<SysUserRole> parameter){
        if(parameter.getParam().getRoleId().isEmpty()){
            return ReturnT.error("必须选择一条角色记录");
        }
        Page<SysUser> page = sysUserRoleService.queryNotSetByPage(parameter);
        return ReturnT.ok(page);
    }
    
    /**
     * 删除角色用户关系
     * @param id 关系id
     * @return 删除结果
     */
    @Operation(summary = "删除角色用户关系", description = "删除角色用户关系",
            parameters = {@Parameter(name = "ids", description = "id")})
    @ApiResponse(responseCode = "2xx",description = "删除角色用户关系")
    @GetMapping("/deleteRoleUserById/{id}")
    @PreAuthorize("hasAuthority('sys:roleUser:delete')")
    @OperateLog(module="系统管理", description = "删除角色用户关系")
    public ReturnT<String> deleteRoleUserById(@PathVariable("id") Serializable id) {
        try{
            SysUserRole sysUserRole = sysUserRoleService.getById(id);
            if(sysUserRole != null && Constant.SUPER_ADMIN_ROLE_ID.equals(sysUserRole.getRoleId())
                && Constant.SUPER_ADMIN.equals(sysUserRole.getUserId())){
                return ReturnT.error("内置用户角色不允许删除");
            }
            sysUserRoleService.removeById(id);
            return ReturnT.ok("删除删除角色用户关系成功");
        }catch(IllegalArgumentException | BusinessException e){
            log.error(e.getMessage(), e);
            return ReturnT.error(e.getMessage());
        }catch(Exception e){
            log.error("删除删除角色用户关系失败", e);
            return ReturnT.error("删除删除角色用户关系失败");
        }
    }
    
    /**
     * 新增用户角色关系
     * @param sysUserRole 用户角色关系
     * @return 结果
     */
    @Operation(summary = "新增用户角色关系", description = "新增用户角色关系")
    @ApiResponse(responseCode = "2xx",description = "新增用户角色关系")
    @PostMapping("/setRoleUserSelectHandle")
    @PreAuthorize("hasAuthority('sys:roleUser:add')")
    @OperateLog(module="系统管理", description = "新增用户角色关系")
    public ReturnT<Boolean> setRoleUserSelectHandle(@RequestBody SysUserRole sysUserRole) {
        try{
            sysUserRole.setId(UuidUtil.get32UUID());
            return ReturnT.ok(sysUserRoleService.save(sysUserRole));
        }catch(Exception e){
            log.error("保存新增用户角色关系失败", e);
            return ReturnT.error("保存新增用户角色关系失败！");
        }
    }

    /**
     * 获取当前用户租户下的角色
     * @return 角色信息
     */
    @ApiResponse(responseCode = "2xx",description = "获取当前用户租户下的角色")
    @GetMapping("/getTenantRoleList")
    public ReturnT<List<SysRole>> getTenantRoleList(){
        return ReturnT.ok(sysRoleService.listByTenantId(UserUtil.getCurrentUser().getTenantId()));
    }
}
